
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:im_app/im/util/UiUtil.dart';

import '../../util/DialogUtil.dart';
import '../../util/ImConstant.dart';
import '../../util/ImSingleton.dart';
import '../bloc/SelectGroupUsersCubit.dart';
import '../bloc/WebRtcCubit.dart';
import '../view/SelectGroupUsersView.dart';
import '../view/WebRtcAudioView.dart';
import '../view/WebRtcVideoView.dart';

class SelectGroupUsersPage extends StatelessWidget {

  final String groupCode;

  const SelectGroupUsersPage({ required this.groupCode, super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _buildAppbar(context),
      backgroundColor: ImConstant.IM_MAIN_BACKGROUND_COLOR,
      body: SafeArea(
        left: false,
        right: false,
        child: _buildBody(context),
      ),
    );
  }

  AppBar _buildAppbar(BuildContext context) {
    return AppBar(
      leading: GestureDetector(
        child: const Padding(padding: EdgeInsets.only(left: 20), child: Text('取消'),),
        onTap: () {
          Navigator.of(context).pop();
        },
      ),
      title: const Text(
        "请选择用户",
        style: TextStyle(fontSize: ImConstant.IM_DEFAULT_SIZE, fontWeight: FontWeight.w500),
      ),
      actions: [
        GestureDetector(
          child: const Padding(padding: EdgeInsets.only(right: 20), child: Text('提 交'),),
          onTap: () => submitEvent(context),
        )
      ],
      toolbarHeight: ImConstant.IM_APP_BAR_HEIGTH,
      backgroundColor: ImConstant.IM_MAIN_BACKGROUND_COLOR,
      centerTitle: true,
    );
  }

  _buildBody(BuildContext context) {
    return SelectGroupUsersView(groupCode: groupCode);
  }

  void submitEvent(BuildContext context) {
    var selectGroupUsersCubit = context.read<SelectGroupUsersCubit>();
    var selectedUsers = selectGroupUsersCubit.state.selectedUsers;
    if (selectedUsers.length > ImConstant.WEBRTC_USER_LIMIT) {
      UiUtil.showSnackBar(context, '视频群聊最多不能超过${ImConstant.WEBRTC_USER_LIMIT}人');
      return;
    }

    var userSet = selectedUsers.toSet();
    var webRtcCubit = context.read<WebRtcCubit>();

    OverlayEntry entry;
    if (!selectGroupUsersCubit.isAudio) {
      var dialog = WebRtcVideoView() ;
      entry = showOverlay(context, dialog);
      dialog.overlayEntry = entry;
    } else {
      var dialog = WebRtcAudioView();
      entry = showOverlay(context, dialog);
      dialog.overlayEntry = entry;
    }

    var screenWidth = MediaQuery.of(context).size.width; // 获取屏幕宽度
    var screenHeight = MediaQuery.of(context).size.height; // 获取屏幕高度

    ImSingleton.getInstance().session.putData("webRtcOverlay", entry);
    webRtcCubit.add(WebRtcInitiateEvent(context, userSet, entry, selectGroupUsersCubit.isAudio, screenWidth, screenHeight));
  }

}